#!/bin/bash
#
# Copyright 2015-2017 Adrian DC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

# === Standalone Source Helper ===
# source <(curl -Ls https://github.com/AdrianDC/android_development_shell_tools/raw/master/android_build_helpers.rc)

# === Make with Jobs ===
function makej()
{
  # Usage: makej <parameters> (Helper to 'make -jPROCESSORS')
  make -j"$(grep -c ^processor /proc/cpuinfo)" "${@}";
}

# === Make with Jobs and SCHED_BATCH ===
function makes()
{
  # Usage: makes <parameters> (Helper to 'make -jPROCESSORS' with SCHED_BATCH)

  # Variables
  local ret;
  local time_start;

  # Store compilation start time
  time_start=$(date +%s);

  # Makes with SCHED_BATCH and all processors
  schedtool -B -n 10 -e ionice -n 7 make -j"$(grep -c ^processor /proc/cpuinfo)" "${@}";
  ret=${?};

  # Acquire build time result
  __maketimestring 'makes' "${ret}" "${time_start}";

  # Present build log
  echo '';
  if [ ${ret} -eq 0 ]; then
    echo -e "  \e[1;32m#### ${BUILD_RESULT} ####\e[0m";
  else
    echo -e " \e[1;31m#### ${BUILD_RESULT} ####\e[0m";
  fi;
  echo '';
}

# === Internal make time string builder ===
function __maketimestring()
{
  # Usage
  if [ -z "${1}" ] || [ -z "${2}" ] || [ -z "${3}" ]; then
    echo '';
    echo ' Usage: __maketimestring <tag> <return_value> <time_start> (Internal make time string builder)';
    echo '';
    return;
  fi;

  # Variables
  local time_diff;
  local time_hours;
  local time_minutes;
  local time_seconds;
  local time_string;

  # Calculate compilation times
  time_diff=$(($(date +%s) - ${3}));
  time_seconds=$((time_diff % 60));
  time_diff=$((time_diff / 60));
  time_minutes=$((time_diff % 60));
  time_hours=$((time_diff / 60));

  # Build success or failure log
  if [ "${2}" -eq 0 ] ; then
    time_string="${1}: Completed in";
  else
    time_string="${1}: Failed after";
  fi;

  # Build time log
  if [ ${time_hours} -gt 0 ]; then
    time_string=$(printf "${time_string} %02g:%02g:%02g (hh:mm:ss)" ${time_hours} ${time_minutes} ${time_seconds});
  elif [ ${time_minutes} -gt 0 ] ; then
    time_string=$(printf "${time_string} %02g:%02g (mm:ss)" ${time_minutes} ${time_seconds});
  elif [ ${time_seconds} -gt 0 ] ; then
    time_string=$(printf "${time_string} %s seconds" ${time_seconds});
  fi;

  # Export result as BUILD_RESULT
  export BUILD_RESULT=${time_string};
}
